<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('基本信息') }}</span>
      </div>
      <el-row>
        <el-col :span="12" :style="{ height: Wheight }">
          <el-form-item :label="$t('公司名称')" prop="company.companyName">
            <span slot="label"> {{ $t(companyLabel) }} </span>
            <el-autocomplete
              v-model="form.company.companyName"
              class="inline-input"
              :fetch-suggestions="companyQuerySearch"
              :placeholder="$t(companyLabel)"
              :trigger-on-focus="false"
              :maxlength="100"
              @select="companyHandleSelect"
            >
              <template v-if="form.id" slot="append" @click="companyHandleSelect">
                <router-link
                  target="_blank"
                  :to="{path:'/company/base/companyBaseHome',query:{companyId:form.companyId}}"
                  class="link_a"
                >{{ $t('查看标的公司信息') }}</router-link>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12" :style="{height: Wheight}">
          <el-form-item :label="$t('项目名称')" prop="dealName">
            <el-input v-if="!form.id" v-model="form.dealName" :placeholder="$t('项目名称')" show-word-limit :maxlength="100" @change="checkDealNameExist()" />
            <el-input v-else v-model="form.dealName" show-word-limit :maxlength="100" @change="checkDealNameExist()" />
            <!--              <template v-if="form.id" slot="append">-->
            <!--                <span @click="chartOpenHandle">{{ $t('查看投资架构图') }}</span>-->
            <!--              </template>-->
            <!--            </el-input>-->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目类型')" prop="dealType">
            <dictSelect
              v-model="form.dealType"
              :disabled="(form.dealType !== undefined && form.id !== undefined) || !dealTypeUpdate"
              dictionary="deal_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目状态')" prop="dealStatus">
            <dictSelect
              v-model="form.dealStatus"
              dictionary="deal_status"
              :disabled="dealStatusModify"
              @change="dealStatusChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目负责人')" prop="personCharge">
            <UserSelect
              v-model="form.personCharge"
              :placeholder="$t('项目负责人')"
              @change="personChargeChange($event)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('投资币种')" prop="currency">
            <el-select v-model="form.currency" :placeholder="$t('投资币种')">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('行业大类')" prop="dealBaseLease.industryFirst">
            <dict-select
              v-model="form.dealBaseLease.industryFirst"
              dictionary="lease_industry_category"
              :placeholder="$t('请选择')"
              @change="changeIndustryFirst"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('行业小类')" prop="dealBaseLease.industrySecond">
            <dict-select
              v-if="refreshDictionary"
              v-model="form.dealBaseLease.industrySecond"
              :dictionary="'lease_industry_category_' + form.dealBaseLease.industryFirst"
              :placeholder="$t('请选择')"
            />
          </el-form-item>
        </el-col>
        <!-- 省市 -->
        <Area ref="cityZj" :buss-data="form.company" :prop-s-f="'company.provinceRegistered'" :prop-city="'company.cityRegistered'" :prop-district="'company.districtRegistered'" />
        <el-col :span="12">
          <el-form-item :label="$t('预计投资金额') + $t('金额单位')" prop="amountInvestmentEstimate">
            <Money v-model="form.amountInvestmentEstimate" unit="w" :placeholder="$t('预计投资金额')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('企业性质')" prop="dealBaseLease.enterpriseNature">
            <dict-select
              v-model="form.dealBaseLease.enterpriseNature"
              dictionary="deal_lease_enterprise_nature"
              :placeholder="$t('企业性质')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('所属公司')" prop="dealBaseLease.affiliatedCompany">
            <tree-select
              v-model="form.dealBaseLease.affiliatedCompany"
              :default-expand-all="true"
              node-key="id"
              :data="companyOptions"
              :placeholder="$t('请选择')"
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('责任部门')" prop="dealBaseLease.responsibleDepartment">
            <dept-select
              v-model="form.dealBaseLease.responsibleDepartment"
              :default-expand-all="true"
              :data="deptOptions"
              :placeholder="$t('请选择')"
            >
              <label
                slot="option-label"
                slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                :class="labelClassName"
              >
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </dept-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('承揽人')" prop="dealBaseLease.contractor">
            <UserSelect v-model="form.dealBaseLease.contractor" :multiple="true" :placeholder="$t('承揽人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('承做人')" prop="dealBaseLease.undertaker">
            <UserSelect v-model="form.dealBaseLease.undertaker" :multiple="true" :placeholder="$t('承做人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('担保人')" prop="dealBaseLease.guarantee">
            <UserSelect v-model="form.dealBaseLease.guarantee" :multiple="true" :placeholder="$t('担保人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('交易模式')" prop="dealBaseLease.transactionMode">
            <dict-select
              v-model="form.dealBaseLease.transactionMode"
              dictionary="deal_lease_transaction_mode"
              :placeholder="$t('交易模式')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('回款状态')" prop="dealBaseLease.collectionStatus">
            <dict-select
              v-model="form.dealBaseLease.collectionStatus"
              dictionary="deal_lease_collection_status"
              :placeholder="$t('回款状态')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('客户来源')" prop="dealBaseLease.customerSource">
            <dict-select
              v-model="form.dealBaseLease.customerSource"
              dictionary="deal_lease_customer_source"
              :placeholder="$t('客户来源')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('来源说明')" prop="dealBaseLease.sourceDescription">
            <el-input v-model="form.dealBaseLease.sourceDescription" :placeholder="$t('来源说明')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('租赁标的物')" prop="dealBaseLease.leaseSubjectMatter">
            <el-input v-model="form.dealBaseLease.leaseSubjectMatter" :placeholder="$t('租赁标的物')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('租赁期限(年)')" prop="dealBaseLease.leaseTerm">
            <el-input v-model="form.dealBaseLease.leaseTerm" :placeholder="$t('租赁期限(年)')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('租赁利率（%）')" prop="dealBaseLease.leaseRate">
            <Ratio
              v-model="form.dealBaseLease.leaseRate"
              :precision="4"
              :controls="false"
              :min="0"
              :max="100"
              :placeholder="$t('租赁利率(%)')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('XIRR（%）')" prop="dealBaseLease.xirr">
            <Ratio
              v-model="form.dealBaseLease.xirr"
              :precision="4"
              :controls="false"
              :min="0"
              :max="100"
              :placeholder="$t('XIRR(%)')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('手续费/咨询费') + $t('金额单位')" prop="dealBaseLease.serviceCharge">
            <Money v-model="form.dealBaseLease.serviceCharge" unit="w" :placeholder="$t('手续费/咨询费')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('保证金') + $t('金额单位')" prop="dealBaseLease.bond">
            <Money v-model="form.dealBaseLease.bond" unit="w" :placeholder="$t('保证金')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('担保主体')" prop="dealBaseLease.guaranteeSubject">
            <el-input v-model="form.dealBaseLease.guaranteeSubject" :placeholder="$t('担保主体')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('担保方式')" prop="dealBaseLease.guaranteeMethod">
            <el-input v-model="form.dealBaseLease.guaranteeMethod" :placeholder="$t('担保方式')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('担保方评级')" prop="dealBaseLease.guarantorRating">
            <el-input v-model="form.dealBaseLease.guarantorRating" :placeholder="$t('担保方评级')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('其他担保方式')" prop="dealBaseLease.otherGuaranteeMethods">
            <el-input v-model="form.dealBaseLease.otherGuaranteeMethods" :placeholder="$t('其他担保方式')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('还款方式')" prop="dealBaseLease.repaymentMethod">
            <el-input v-model="form.dealBaseLease.repaymentMethod" :placeholder="$t('还款方式')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('资金用途')" prop="dealBaseLease.useOfFunds">
            <el-input v-model="form.dealBaseLease.useOfFunds" :placeholder="$t('资金用途')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('开户行名称')" prop="dealBaseLease.nameOfDepositBank">
            <el-autocomplete
              v-model="form.dealBaseLease.nameOfDepositBank"
              popper-class="my-autocomplete"
              :fetch-suggestions="querySearch"
              :maxlength="100"
              :placeholder="$t('收款方名称')"
              @select="handleSelect($event)"
            >
              <i slot="suffix" class="el-icon-edit" @click="handleIconClick">.</i>
              <template slot-scope="{ item }">
                <div class="name">{{ item.value }}</div>
                <span class="addr">{{ item.address }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('账户名称')" prop="dealBaseLease.titleOfAccount">
            <el-input v-model="form.dealBaseLease.titleOfAccount" :placeholder="$t('账户名称')" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('银行账号')" prop="dealBaseLease.bankAccount">
            <el-input v-model="form.dealBaseLease.bankAccount" :placeholder="$t('银行账号')" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.dealStatus ==='ZZ'" :span="24">
          <el-form-item :label="$t('终止原因')" prop="terminationReason">
            <el-input v-model="form.terminationReason" type="textarea" :placeholder="$t('终止原因')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 团队成员 -->
      <div v-if="form.id === undefined" class="area-header" style="margin-top: 15px;">
        <span class="area-header-title">{{ $t('团队成员') }}</span>
      </div>
      <div v-if="form.id === undefined" style="margin-top:15px;">
        <el-table :data="form.dealTeamList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用户名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用户名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.user.userId'" :rules="dealTeamListRules.userId">
                <UserSelect v-model="scope.row.user.userId" :disabled="scope.row.disabled" :placeholder="$t('选择用户')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('参与角色')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('参与角色') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.role'" :rules="dealTeamListRules.role">
                <el-select v-model="scope.row.role" :disabled="scope.row.disabled && scope.row.role === 'F'" :placeholder="$t('参与角色')">
                  <el-option
                    v-for="dict in roleOptions"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                    :disabled="dict.dictValue === 'F' || dict.dictLabel === '项目负责人'"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('备注') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.remark'">
                <el-input v-model="scope.row.remark" type="textarea" maxlength="2000" class="fileTextarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!btnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:dealbase:edit']" :disabled="scope.row.disabled" size="small" type="text" icon="el-icon-delete" @click="delTeam(scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!btnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addTeam()">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" has-permi="deal:dealbase" data-type="deal_base" :business-type="form.dealType" :select-business-data="false" />
    </el-form>
    <div v-show="!btnHide" slot="footer" class="dialog-footer">
      <SaveBtn has-permi="deal:dealbase" :cancel-show="openLocation === undefined" :bus-data="form" :cache-key="'deal_base_' + form.dealType" @cancelCustom="cancelCustom" />
    </div>
    <el-dialog :title="$t('')" :visible.sync="chartOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <invest-structure-chart ref="investStructureChart" :chart-data="chartData" :btn-list="btnList" />
    </el-dialog>
    <!-- 收款方历史 -->
    <el-dialog :visible.sync="payeeHistoryOpen" :title="$t('收款方历史')" :destroy-on-close="true" custom-class="folderOpen" style=" text-align: left;" append-to-body :close-on-click-modal="false" :lock-scroll="false">
      <oaPayeeHistoryList ref="oaPayeeHistoryList" />
    </el-dialog>
  </div>
</template>

<script>

import oaPayeeHistoryList from '@/views/oa/payment/oaPaymentHistoryList.vue'
import Area from '@/components/Area'
import TreeSelect from '@/components/TreeSelect/index'
import investStructureChart from '@/views/deal/base/investStructureChart.vue'
import { saveDealBase, getDealBase, getDealBaseByName } from '@/api/base/deal/dealBase'
import { companyListByName } from '@/api/company/base/companyBase'
import { investChartData } from '@/api/fund/fundBase'
import { saveDealInvestment } from '@/api/deal/investment/dealInvestment'
import { getDeptInfoByUserId, treeselect } from '@/api/system/dept'
import { getPayeeHistory } from '@/api/oa/payment/oaPayment'

export default {
  components: {
    oaPayeeHistoryList,
    Area,
    TreeSelect,
    investStructureChart
  },
  data() {
    return {
      loading: false,
      Wheight: '83px',
      // 公司名称label
      companyLabel: '承租人名称',
      // 项目类型是否可以修改
      dealTypeUpdate: true,
      // 表单参数
      form: {
        company: {},
        dealBaseLease: {}
      },
      // 项目状态是否可以修改
      dealStatusModify: false,
      // 是否隐藏保存等按钮
      btnHide: false,
      // 打开页面的位置，如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
      openLocation: undefined,
      // 表单校验
      rules: {
        investmentType: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        dealName: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        dealType: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        personCharge: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        dealSource: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        dealStatus: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        terminationReason: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        currency: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        amountInvestmentEstimate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        'company.companyName': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.industryFirst': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.industrySecond': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.cityRegistered': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.provinceRegistered': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.nameOfDepositBank': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.titleOfAccount': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.bankAccount': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.contractor': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.undertaker': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.guarantee': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.affiliatedCompany': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.responsibleDepartment': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseLease.enterpriseNature': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      dealTeamListRules: {
        userId: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        role: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      // 币种
      currencyOptions: [],
      // 项目类型
      dealTypeOptions: [],
      // 项目来源
      dealSourceOptions: [],
      // 关注等级
      levelConcernOptions: [],
      // 项目ID
      dealId: this.$route.query.id,
      // 天眼查查询条件
      tycParam: {
        id: '',
        companyName: '',
        tycId: ''
      },
      chartOpen: false,
      chartData: {},
      // 参与角色 字典deal_team_role字典
      roleOptions: [],
      companyOptions: [],
      deptOptions: [],
      refreshDictionary: true,
      payeeHistoryOpen: false,
      btnList: [],
      restaurants: []
    }
  },
  watch: {
  },
  mounted() {
    this.$bus.$emit('async_done')
    this.restaurants = this.loadAll()
  },
  created() {
    this.getTreeselect()
  },
  methods: {
    // 项目状态变更
    dealStatusChange(val) {
      if (val === 'CB') {
        this.rules.personCharge = null
      } else {
        this.rules.personCharge = [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      }
    },
    // 初始化数据
    async init(data) {
      this.loading = true
      await Promise.all(this.getDictOptions())
      if (data !== undefined && data !== null && data.id !== null && data.id !== '' && data.id !== undefined) {
        this.loading = true
        // this.reset()
        getDealBase(data.id).then(response => {
          this.form = response.data
          this.$nextTick(() => {
            if (this.$refs.cityZj?.initCity !== undefined) {
              this.$refs.cityZj.initCity()
            }
          })
          this.form.dealBaseLease.guarantee = this.form.dealBaseLease.guarantee === null ? undefined : JSON.parse(this.form.dealBaseLease.guarantee)
          this.form.dealBaseLease.contractor = this.form.dealBaseLease.contractor === null ? undefined : JSON.parse(this.form.dealBaseLease.contractor)
          this.form.dealBaseLease.undertaker = this.form.dealBaseLease.undertaker === null ? undefined : JSON.parse(this.form.dealBaseLease.undertaker)
          // 储备项目，项目负责人设置为非必填
          this.dealStatusChange(this.form.dealStatus)
          this.loading = false
        })
      } else {
        this.reset(data)
        this.addTeamPerson()
        this.loading = false
      }
    },
    // 表单重置
    reset(data) {
      console.log('重置表单')
      this.form = {
        id: undefined,
        dealName: undefined,
        dealNamePinyin: undefined,
        personCharge: this.$store.state.user.userId,
        dealSource: undefined,
        dateTouchFirst: undefined,
        dateInvestmentEstimate: undefined,
        amountInvestmentEstimate: undefined,
        currency: 'CNY',
        levelConcern: undefined,
        dealIntroduction: undefined,
        dealStrongPoint: undefined,
        dealScruple: undefined,
        dealStatus: undefined,
        companyURL: undefined,
        transactionDetails: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        delFlag: undefined,
        company: {
          companyName: '',
          companyShortName: undefined,
          industryFirst: undefined,
          industrySecond: undefined,
          provinceRegistered: undefined,
          cityRegistered: undefined
        },
        dealBaseLease: {
          enterpriseNature: undefined,
          affiliatedCompany: undefined,
          responsibleDepartment: undefined,
          contractor: [this.$store.state.user.userId],
          undertaker: [this.$store.state.user.userId],
          guarantee: [this.$store.state.user.userId],
          transactionMode: undefined,
          collectionStatus: undefined,
          customerSource: undefined,
          sourceDescription: undefined,
          leaseSubjectMatter: undefined,
          leaseTerm: undefined,
          leaseRate: undefined,
          xirr: undefined,
          serviceCharge: undefined,
          bond: undefined,
          guaranteeSubject: undefined,
          guaranteeMethod: undefined,
          guarantorRating: undefined,
          otherGuaranteeMethods: undefined,
          repaymentMethod: undefined,
          useOfFunds: undefined,
          nameOfDepositBank: undefined,
          titleOfAccount: undefined,
          bankAccount: undefined
        },
        fileList: []
      }
      if (data !== undefined && data != null) {
        if (data.dealStatus !== undefined) {
          this.dealStatusModify = true
          this.form.dealStatus = data.dealStatus
          // 储备项目，项目负责人设置为非必填
          this.dealStatusChange(this.form.dealStatus)
        }
        if (data.dealType !== undefined) {
          this.dealTypeUpdate = false
          this.form.dealType = data.dealType
        }
      }
      // 获取当前用户所属部门及公司
      getDeptInfoByUserId(this.$store.state.user.userId).then(response => {
        console.log(response)
        if (response.data !== null) {
          this.form.dealBaseLease.responsibleDepartment = response.data.id
          var tempDept = response.data.ancestors.split(',')
          if (tempDept !== undefined && tempDept !== null) {
            this.companyOptions && this.companyOptions.forEach(item => {
              if (tempDept.includes(item.id)) {
                this.form.dealBaseLease.affiliatedCompany = item.id
              }
            })
          }
        }
      })
      this.resetForm('form')
    },
    changeIndustryFirst() {
      this.form.company.industrySecond = ''
      this.refreshDictionary = false
      this.$nextTick(() => {
        this.refreshDictionary = true
      })
      this.$forceUpdate()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formLeaseOpen !== undefined) {
        this.$parent.$parent.formLeaseOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
      if (this.$parent.$parent.getViewList !== undefined) {
        this.$parent.$parent.getViewList()
      }
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
      })
      var query = { 'deptType': 'GS' }
      treeselect(query).then(response => {
        this.companyOptions = response.data
      })
    },
    // 校验数据必填等信息
    validateData: function() {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(validTop => {
          if (validTop) {
            resolve()
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    /** 提交按钮bottom */
    submitForm: function() {
      return new Promise((resolve, reject) => {
        this.validateData().then(() => {
          this.loading = true
          this.form.dealBaseLease.guarantee = JSON.stringify(this.form.dealBaseLease.guarantee)
          this.form.dealBaseLease.contractor = JSON.stringify(this.form.dealBaseLease.contractor)
          this.form.dealBaseLease.undertaker = JSON.stringify(this.form.dealBaseLease.undertaker)
          saveDealBase(this.form).then(response => {
            if (response.code === 200) {
              // 如果在母基金页面新建的项目, 则给这个新建的项目添加一个当前母基金的出资人
              if (this.$route.query.fundType === 'fof') {
                const dealInvestor = {
                  dealId: response.data.id,
                  investorId: this.$route.query.id,
                  investorType: 'fund',
                  currency: this.form.currency ? this.form.currency : 'CNY',
                  dateInvestmentEstimate: new Date(),
                  amountInvestmentEstimate: 0
                }
                saveDealInvestment(dealInvestor).then(() => {
                  this.closeForm()
                })
              }
              // 如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
              if (this.openLocation === 'Home') {
                // 项目里边保存
                this.loading = false
              }
              if (this.$parent.$parent.$parent?.formProperty !== undefined) {
                this.$parent.$parent.$parent.formProperty = false
                this.$parent.$parent.$parent.init()
              }
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
              resolve()
            } else {
              this.msgError(response.msg)
              this.loading = false
              reject()
            }
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
          reject()
        })
      })
    },
    // 标的公司查询
    companyQuerySearch(queryString, cb) {
      companyListByName(queryString).then(res => {
        if (res.code === 200) {
          cb(res.data)
        }
      })
    },
    // 标的公司选择后事件
    companyHandleSelect(item) {
      this.form.dealName = this.form.company.companyName
      this.form.company.tycId = item.id
      this.checkDealNameExist()
    },
    // 判断项目名称是否存在
    checkDealNameExist() {
      const dealName = this.form.dealName
      if (dealName === '' || dealName === undefined) {
        this.rules.dealName = [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
        return
      }
      this.tycParam.dealName = dealName

      getDealBaseByName(this.tycParam).then(res => {
        if (res.data !== null && res.data.id !== this.form.id) {
          this.rules.dealName = [{ required: true, message: this.$t('项目名称不能重复'), trigger: 'change' }]
          this.form.dealName = ''
        }
      })
    },
    getDictOptions() {
      return [
        // 币种
        this.getDicts('currency').then(response => {
          this.currencyOptions = response.data
        }),
        // 项目类型
        this.getDicts('deal_type').then(response => {
          this.dealTypeOptions = response.data
        }),
        // 项目来源
        this.getDicts('deal_source').then(response => {
          this.dealSourceOptions = response.data
        }),
        // 关注等级
        this.getDicts('level_concern').then(response => {
          this.levelConcernOptions = response.data
        }),
        // 项目阶段
        this.getDicts('deal_stage').then(response => {
          this.dealStageOptions = response.data
        }),
        // 团队成员字典
        this.getDicts('deal_team_role').then(response => {
          this.roleOptions = response.data
        })
      ]
    },
    loadAll() {
      var temp = []
      getPayeeHistory().then(reponse => {
        if (reponse.data !== null) {
          for (var i = 0; i < reponse.data.length; i++) {
            var obj = {
              'value': reponse.data[i].payeeName,
              'address': reponse.data[i].depositBank + '|' + reponse.data[i].accountTitle + '|' + reponse.data[i].bankNumber
            }
            temp.push(obj)
          }
        }
      })
      return temp
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().includes(queryString.toLowerCase()))
      }
    },
    // 收款方选择后触发
    handleSelect(rowItem) {
      this.form.dealBaseLease.nameOfDepositBank = rowItem.value
      var arr = rowItem.address.split('|')
      this.form.dealBaseLease.titleOfAccount = arr[0]
      this.form.dealBaseLease.bankAccount = arr[1]
    },
    // 收款方旁边的小按钮
    handleIconClick() {
      this.payeeHistoryOpen = true
    },
    chartOpenHandle() {
      this.chartOpen = true
      investChartData(this.form.id).then(res => {
        this.chartData = res.data
      })
      this.$nextTick(() => {
        this.$refs.investStructureChart.initCompany({ busId: this.form.company.id, busType: 'company', busName: this.form.company.companyName })
      })
    },
    personChargeChange(personCharge) {
      console.log('项目负责人change: ', personCharge)
      if (this.form) {
        if (personCharge === this.$store.state.user.userId) {
          if (this.form.dealTeamList !== undefined && this.form.dealTeamList !== null) {
            this.form.dealTeamList.forEach((item, index) => {
              if (item.disabled && item.role === 'F') {
                item.user.userId = personCharge
              }
              if (item.user.userId === personCharge && item.role !== 'F') {
                this.form.dealTeamList.splice(index, 1)
              }
            })
          }
        } else {
          // 如果项目负责人不是创建人本人, 修改默认添加的项目负责人, 并添加自己为项目成员
          if (this.form.dealTeamList !== undefined && this.form.dealTeamList !== null) {
            var isExist = false
            this.form.dealTeamList.forEach((item) => {
              if (item.disabled && item.role === 'F') {
                item.user.userId = personCharge
              }
              if (item.user.userId === this.$store.state.user.userId && !isExist) {
                isExist = true
              }
            })
            // 添加自己为项目成员
            if (!isExist) {
              this.addTeam({
                user: { userId: this.$store.state.user.userId },
                role: 'C',
                joinTime: new Date(),
                leave: 'N',
                disabled: true
              })
            }
          }
        }
      }
    },
    delTeam(index) {
      this.form.dealTeamList.splice(index, 1)
    },
    addTeamPerson() {
      this.addTeam({ user: { userId: this.$store.state.user.userId }, role: 'F', joinTime: new Date(), leave: 'N', disabled: true })
    },
    addTeam(data) {
      var row = {
        id: undefined,
        user: { userId: '' },
        role: 'C',
        joinTime: new Date(),
        leave: 'N',
        remark: undefined,
        disabled: false
      }
      if (data !== undefined) {
        row = data
      }
      if (!(this.form.dealTeamList instanceof Array)) {
        this.$set(this.form, 'dealTeamList', [])
      }
      this.$nextTick(() => {
        this.form.dealTeamList.push(row)
      })
    },
    cancelCustom() {
      this.$parent.$parent.formLeaseOpen = false
    }
  }
}
</script>

<style scoped>
.tianyan{
  border: 1px solid #DCDFE6;
  width: 17%;
  border-radius: 5px;
  height: 36px;
  float: right;
  text-align: right;
  padding-right: 15px;
  border-left: 0px;
  color: #1E9FFF;
  margin-top: -37px;
  font-size: 13px;
}
</style>
